var express = require('express');
var router = express.Router();
var bkcModel = require('../db/bkc');

// 获取所有订单
router.get('/orders', async function(req, res, next) {
  try {
    const orders = await bkcModel.find({ orderId: { $exists: true } }).sort({ orderTime: -1 });
    res.json({
      success: true,
      data: orders,
      message: '获取订单列表成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取订单列表失败',
      error: error.message
    });
  }
});

// 根据状态获取订单
router.get('/orders/status/:status', async function(req, res, next) {
  try {
    const { status } = req.params;
    let query = {};
    
    if (status !== '全部') {
      query.orderStatus = status;
    }
    
    const orders = await bkcModel.find({ ...query, orderId: { $exists: true } }).sort({ orderTime: -1 });
    res.json({
      success: true,
      data: orders,
      message: '获取订单列表成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取订单列表失败',
      error: error.message
    });
  }
});

// 创建订单
router.post('/orders', async function(req, res, next) {
  try {
    const orderData = req.body;
    const newOrder = new bkcModel(orderData);
    const savedOrder = await newOrder.save();
    
    res.json({
      success: true,
      data: savedOrder,
      message: '创建订单成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '创建订单失败',
      error: error.message
    });
  }
});

// 更新订单状态
router.put('/orders/:orderId/status', async function(req, res, next) {
  try {
    const { orderId } = req.params;
    const { orderStatus } = req.body;
    
    const updatedOrder = await bkcModel.findOneAndUpdate(
      { orderId },
      { orderStatus },
      { new: true }
    );
    
    if (!updatedOrder) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    res.json({
      success: true,
      data: updatedOrder,
      message: '更新订单状态成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新订单状态失败',
      error: error.message
    });
  }
});

// 获取订单详情
router.get('/orders/:orderId', async function(req, res, next) {
  try {
    const { orderId } = req.params;
    const order = await bkcModel.findOne({ orderId });
    
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    res.json({
      success: true,
      data: order,
      message: '获取订单详情成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取订单详情失败',
      error: error.message
    });
  }
});

// 删除订单
router.delete('/orders/:orderId', async function(req, res, next) {
  try {
    const { orderId } = req.params;
    const deletedOrder = await bkcModel.findOneAndDelete({ orderId });
    
    if (!deletedOrder) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    res.json({
      success: true,
      message: '删除订单成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '删除订单失败',
      error: error.message
    });
  }
});

// 初始化订单数据
router.post('/orders/init', async function(req, res, next) {
  try {
    // 检查是否已有订单数据
    const existingOrders = await bkcModel.countDocuments({ orderId: { $exists: true } });
    
    if (existingOrders > 0) {
      return res.json({
        success: false,
        message: '订单数据已存在，无需重复初始化'
      });
    }
    
    // 创建10条订单数据
    const ordersData = [
      {
        orderId: 'ORD001',
        orderType: '代取快递',
        orderStatus: '待付款',
        orderTitle: '顺丰快递代取',
        orderDescription: '顺丰快递，单号：SF1234567890，取件码：1234',
        orderAmount: 5.00,
        orderAddress: '菜鸟驿站（图书馆对面）',
        orderPhone: '13800138000',
        orderTime: new Date('2025-01-15 10:30:00'),
        pickupTime: null,
        deliveryTime: null,
        completeTime: null,
        riderId: '',
        riderName: '',
        riderPhone: '',
        customerId: 'CUST001',
        customerName: '张三',
        customerPhone: '13800138000',
        paymentMethod: '微信',
        paymentStatus: '未支付',
        remark: '请尽快取件，谢谢',
        images: [],
        tags: ['快递', '顺丰']
      },
      {
        orderId: 'ORD002',
        orderType: '代取外卖',
        orderStatus: '待接单',
        orderTitle: '美团外卖代取',
        orderDescription: '美团外卖，订单号：MT987654321，商家：黄焖鸡米饭',
        orderAmount: 8.00,
        orderAddress: '美团外卖柜（宿舍楼下）',
        orderPhone: '13800138001',
        orderTime: new Date('2025-01-15 11:15:00'),
        pickupTime: null,
        deliveryTime: null,
        completeTime: null,
        riderId: '',
        riderName: '',
        riderPhone: '',
        customerId: 'CUST002',
        customerName: '李四',
        customerPhone: '13800138001',
        paymentMethod: '支付宝',
        paymentStatus: '已支付',
        remark: '请小心取餐，不要洒了',
        images: [],
        tags: ['外卖', '美团']
      },
      {
        orderId: 'ORD003',
        orderType: '代取外卖',
        orderStatus: '待取货',
        orderTitle: '饿了么外卖代取',
        orderDescription: '饿了么外卖，订单号：EL555666777，商家：麻辣烫',
        orderAmount: 6.00,
        orderAddress: '饿了么外卖柜（教学楼门口）',
        orderPhone: '13800138002',
        orderTime: new Date('2025-01-15 12:00:00'),
        pickupTime: new Date('2025-01-15 12:30:00'),
        deliveryTime: null,
        completeTime: null,
        riderId: 'RIDER001',
        riderName: '王五',
        riderPhone: '13900139000',
        customerId: 'CUST003',
        customerName: '王六',
        customerPhone: '13800138002',
        paymentMethod: '微信',
        paymentStatus: '已支付',
        remark: '请尽快送达',
        images: [],
        tags: ['外卖', '饿了么']
      },
      {
        orderId: 'ORD004',
        orderType: '代取快递',
        orderStatus: '待送达',
        orderTitle: '圆通快递代取',
        orderDescription: '圆通快递，单号：YT111222333，取件码：5678',
        orderAmount: 4.50,
        orderAddress: '菜鸟驿站（食堂旁边）',
        orderPhone: '13800138003',
        orderTime: new Date('2025-01-15 09:00:00'),
        pickupTime: new Date('2025-01-15 09:30:00'),
        deliveryTime: new Date('2025-01-15 10:00:00'),
        completeTime: null,
        riderId: 'RIDER002',
        riderName: '赵七',
        riderPhone: '13900139001',
        customerId: 'CUST004',
        customerName: '钱八',
        customerPhone: '13800138003',
        paymentMethod: '余额',
        paymentStatus: '已支付',
        remark: '请送到宿舍楼下',
        images: [],
        tags: ['快递', '圆通']
      },
      {
        orderId: 'ORD005',
        orderType: '代取外卖',
        orderStatus: '已送达',
        orderTitle: '肯德基外卖代取',
        orderDescription: '肯德基外卖，订单号：KFC888999000，套餐：香辣鸡腿堡套餐',
        orderAmount: 12.00,
        orderAddress: '肯德基外卖柜（校门口）',
        orderPhone: '13800138004',
        orderTime: new Date('2025-01-15 08:00:00'),
        pickupTime: new Date('2025-01-15 08:30:00'),
        deliveryTime: new Date('2025-01-15 09:00:00'),
        completeTime: null,
        riderId: 'RIDER003',
        riderName: '孙九',
        riderPhone: '13900139002',
        customerId: 'CUST005',
        customerName: '周十',
        customerPhone: '13800138004',
        paymentMethod: '支付宝',
        paymentStatus: '已支付',
        remark: '请保持温度',
        images: [],
        tags: ['外卖', '肯德基']
      },
      {
        orderId: 'ORD006',
        orderType: '闲置交易',
        orderStatus: '已完成',
        orderTitle: '二手自行车交易',
        orderDescription: '九成新自行车，品牌：捷安特，价格：200元',
        orderAmount: 200.00,
        orderAddress: '宿舍楼下',
        orderPhone: '13800138005',
        orderTime: new Date('2025-01-14 15:00:00'),
        pickupTime: new Date('2025-01-14 16:00:00'),
        deliveryTime: new Date('2025-01-14 17:00:00'),
        completeTime: new Date('2025-01-14 18:00:00'),
        riderId: 'RIDER004',
        riderName: '吴十一',
        riderPhone: '13900139003',
        customerId: 'CUST006',
        customerName: '郑十二',
        customerPhone: '13800138005',
        paymentMethod: '微信',
        paymentStatus: '已支付',
        remark: '车况很好，很满意',
        images: [],
        tags: ['闲置', '自行车']
      },
      {
        orderId: 'ORD007',
        orderType: '宿舍小店',
        orderStatus: '已完成',
        orderTitle: '零食购买',
        orderDescription: '薯片、可乐、巧克力等零食，总价：25元',
        orderAmount: 25.00,
        orderAddress: '3号宿舍楼',
        orderPhone: '13800138006',
        orderTime: new Date('2025-01-14 20:00:00'),
        pickupTime: new Date('2025-01-14 20:30:00'),
        deliveryTime: new Date('2025-01-14 21:00:00'),
        completeTime: new Date('2025-01-14 21:30:00'),
        riderId: 'RIDER005',
        riderName: '王十三',
        riderPhone: '13900139004',
        customerId: 'CUST007',
        customerName: '李十四',
        customerPhone: '13800138006',
        paymentMethod: '微信',
        paymentStatus: '已支付',
        remark: '零食很新鲜',
        images: [],
        tags: ['零食', '宿舍']
      },
      {
        orderId: 'ORD008',
        orderType: '代取须知',
        orderStatus: '已过期',
        orderTitle: '图书馆书籍代取',
        orderDescription: '《高等数学》教材，图书馆借阅，已过期',
        orderAmount: 3.00,
        orderAddress: '图书馆借阅处',
        orderPhone: '13800138007',
        orderTime: new Date('2025-01-10 14:00:00'),
        pickupTime: null,
        deliveryTime: null,
        completeTime: null,
        riderId: '',
        riderName: '',
        riderPhone: '',
        customerId: 'CUST008',
        customerName: '张十五',
        customerPhone: '13800138007',
        paymentMethod: '微信',
        paymentStatus: '已支付',
        remark: '请尽快处理',
        images: [],
        tags: ['书籍', '图书馆']
      },
      {
        orderId: 'ORD009',
        orderType: '骑手认证',
        orderStatus: '已完成',
        orderTitle: '骑手身份认证',
        orderDescription: '完成骑手身份认证，获得接单权限',
        orderAmount: 0.00,
        orderAddress: '线上认证',
        orderPhone: '13800138008',
        orderTime: new Date('2025-01-13 10:00:00'),
        pickupTime: new Date('2025-01-13 10:30:00'),
        deliveryTime: new Date('2025-01-13 11:00:00'),
        completeTime: new Date('2025-01-13 11:30:00'),
        riderId: 'RIDER006',
        riderName: '刘十六',
        riderPhone: '13900139005',
        customerId: 'CUST009',
        customerName: '陈十七',
        customerPhone: '13800138008',
        paymentMethod: '免费',
        paymentStatus: '已支付',
        remark: '认证成功',
        images: [],
        tags: ['认证', '骑手']
      },
      {
        orderId: 'ORD010',
        orderType: '代取快递',
        orderStatus: '待付款',
        orderTitle: '京东快递代取',
        orderDescription: '京东快递，单号：JD444555666，取件码：9999',
        orderAmount: 6.50,
        orderAddress: '京东快递柜（体育馆旁边）',
        orderPhone: '13800138009',
        orderTime: new Date('2025-01-15 13:00:00'),
        pickupTime: null,
        deliveryTime: null,
        completeTime: null,
        riderId: '',
        riderName: '',
        riderPhone: '',
        customerId: 'CUST010',
        customerName: '杨十八',
        customerPhone: '13800138009',
        paymentMethod: '支付宝',
        paymentStatus: '未支付',
        remark: '请尽快取件',
        images: [],
        tags: ['快递', '京东']
      }
    ];
    
    const result = await bkcModel.insertMany(ordersData);
    
    res.json({
      success: true,
      data: result,
      message: '初始化订单数据成功，共创建10条订单'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '初始化订单数据失败',
      error: error.message
    });
  }
});

// 地址管理相关路由

// 创建新地址
router.post('/addresses', async function(req, res, next) {
  try {
    const addressData = req.body;
    
    // 验证必填字段
    if (!addressData.name || !addressData.phone || !addressData.fullAddress) {
      return res.status(400).json({
        success: false,
        message: '姓名、手机号和完整地址为必填项'
      });
    }
    
    // 生成地址ID
    const addressId = 'ADDR' + Date.now() + Math.random().toString(36).substr(2, 5).toUpperCase();
    
    // 创建地址对象
    const newAddress = new bkcModel({
      addressId: addressId,
      addressType: 'delivery_address',
      name: addressData.name,
      phone: addressData.phone,
      fullAddress: addressData.fullAddress,
      isDefault: addressData.isDefault || false,
      createTime: new Date(),
      updateTime: new Date()
    });
    
    // 如果设置为默认地址，需要将其他地址设为非默认
    if (addressData.isDefault) {
      await bkcModel.updateMany(
        { addressType: 'delivery_address', isDefault: true },
        { isDefault: false }
      );
    }
    
    const savedAddress = await newAddress.save();
    
    res.json({
      success: true,
      data: {
        addressId: savedAddress.addressId,
        name: savedAddress.name,
        phone: savedAddress.phone,
        fullAddress: savedAddress.fullAddress,
        isDefault: savedAddress.isDefault,
        createTime: savedAddress.createTime
      },
      message: '地址创建成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '创建地址失败',
      error: error.message
    });
  }
});

// 获取用户的所有地址
router.get('/addresses', async function(req, res, next) {
  try {
    const addresses = await bkcModel.find({ 
      addressType: 'delivery_address' 
    }).sort({ isDefault: -1, createTime: -1 });
    
    res.json({
      success: true,
      data: addresses,
      message: '获取地址列表成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取地址列表失败',
      error: error.message
    });
  }
});

// 获取指定地址详情
router.get('/addresses/:addressId', async function(req, res, next) {
  try {
    const { addressId } = req.params;
    const address = await bkcModel.findOne({ 
      addressId: addressId,
      addressType: 'delivery_address'
    });
    
    if (!address) {
      return res.status(404).json({
        success: false,
        message: '地址不存在'
      });
    }
    
    res.json({
      success: true,
      data: address,
      message: '获取地址详情成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取地址详情失败',
      error: error.message
    });
  }
});

// 更新地址信息
router.put('/addresses/:addressId', async function(req, res, next) {
  try {
    const { addressId } = req.params;
    const updateData = req.body;
    
    // 验证必填字段
    if (!updateData.name || !updateData.phone || !updateData.fullAddress) {
      return res.status(400).json({
        success: false,
        message: '姓名、手机号和完整地址为必填项'
      });
    }
    
    // 如果设置为默认地址，需要将其他地址设为非默认
    if (updateData.isDefault) {
      await bkcModel.updateMany(
        { addressType: 'delivery_address', isDefault: true },
        { isDefault: false }
      );
    }
    
    updateData.updateTime = new Date();
    
    const updatedAddress = await bkcModel.findOneAndUpdate(
      { addressId: addressId, addressType: 'delivery_address' },
      updateData,
      { new: true }
    );
    
    if (!updatedAddress) {
      return res.status(404).json({
        success: false,
        message: '地址不存在'
      });
    }
    
    res.json({
      success: true,
      data: updatedAddress,
      message: '地址更新成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新地址失败',
      error: error.message
    });
  }
});

// 删除地址
router.delete('/addresses/:addressId', async function(req, res, next) {
  try {
    const { addressId } = req.params;
    const deletedAddress = await bkcModel.findOneAndDelete({ 
      addressId: addressId,
      addressType: 'delivery_address'
    });
    
    if (!deletedAddress) {
      return res.status(404).json({
        success: false,
        message: '地址不存在'
      });
    }
    
    res.json({
      success: true,
      message: '地址删除成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '删除地址失败',
      error: error.message
    });
  }
});

// 设置默认地址
router.put('/addresses/:addressId/default', async function(req, res, next) {
  try {
    const { addressId } = req.params;
    
    // 先将所有地址设为非默认
    await bkcModel.updateMany(
      { addressType: 'delivery_address' },
      { isDefault: false }
    );
    
    // 将指定地址设为默认
    const updatedAddress = await bkcModel.findOneAndUpdate(
      { addressId: addressId, addressType: 'delivery_address' },
      { isDefault: true, updateTime: new Date() },
      { new: true }
    );
    
    if (!updatedAddress) {
      return res.status(404).json({
        success: false,
        message: '地址不存在'
      });
    }
    
    res.json({
      success: true,
      data: updatedAddress,
      message: '设置默认地址成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '设置默认地址失败',
      error: error.message
    });
  }
});

// 初始化地址数据
router.post('/addresses/init', async function(req, res, next) {
  try {
    // 检查是否已有地址数据
    const existingAddresses = await bkcModel.countDocuments({ addressType: 'delivery_address' });
    
    if (existingAddresses > 0) {
      return res.json({
        success: false,
        message: '地址数据已存在，无需重复初始化'
      });
    }
    
    // 创建示例地址数据
    const addressesData = [
      {
        addressId: 'ADDR001',
        addressType: 'delivery_address',
        name: '张三',
        phone: '13800138000',
        fullAddress: '振涛/保理/科技-校园贴吧 科技(东院)—皇悦3期 3-101',
        isDefault: true,
        createTime: new Date('2025-01-15 10:00:00'),
        updateTime: new Date('2025-01-15 10:00:00')
      },
      {
        addressId: 'ADDR002',
        addressType: 'delivery_address',
        name: '李四',
        phone: '13800138001',
        fullAddress: '东院-教学楼 科技(东院)—皇悦2期 2-205',
        isDefault: false,
        createTime: new Date('2025-01-15 11:00:00'),
        updateTime: new Date('2025-01-15 11:00:00')
      },
      {
        addressId: 'ADDR003',
        addressType: 'delivery_address',
        name: '王五',
        phone: '13800138002',
        fullAddress: '西院-图书馆 保理(西院)—阳光小区 1-301',
        isDefault: false,
        createTime: new Date('2025-01-15 12:00:00'),
        updateTime: new Date('2025-01-15 12:00:00')
      }
    ];
    
    const result = await bkcModel.insertMany(addressesData);
    
    res.json({
      success: true,
      data: result,
      message: '初始化地址数据成功，共创建3条地址'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '初始化地址数据失败',
      error: error.message
    });
  }
});

// 原有的路由
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;
